package me.huha.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.huha.client.EmailUtils;
import me.huha.client.utils.PropertiesUtils;
import me.huha.commons.AddressDTO;
import me.huha.commons.Result;
import me.huha.commons.SendEmailDTO;
import me.huha.commons.ToCcBccAddressDTO;
import me.huha.commons.email.EmailSetDTO;
import me.huha.commons.email.PropertiesDTO;
import me.huha.commons.email.UserEmailDTO;
import me.huha.service.EmailService;
import me.huha.tools.Invokers;
import me.huha.tools.Invokers.Invoker;
import me.huha.utils.DownLoadUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Title: EmailServiceImpl.java
 * @Author: Yepx
 * @mail: yepx2013@gmail.com
 * @CreateTime: 2017年9月29日 上午11:20:32
 * @Todo: 发送邮件
 */
public class EmailServiceImpl implements EmailService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private String account;
	private String pass;
	private String getproperStr;
	private String sendproperStr;
	
	public void setAccount(String account) {
		this.account = account;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public void setGetproperStr(String getproperStr) {
		this.getproperStr = getproperStr;
	}

	public void setSendproperStr(String sendproperStr) {
		this.sendproperStr = sendproperStr;
	}

	@Override
	public Result<Boolean> sendEmailByAccount(final Map<String, String> extendMap, final ToCcBccAddressDTO toCcBccAddress, final String title, final String content, final String fileJsonArr) {

		return Invokers.$(new Invoker<Boolean>() {

			@Override
			public Boolean apply() {
				try{
					//String account = "zhime@chinasunfun.com";
					//String pass = "1qaz@WSX";
					//String getproperStr = "{\"host\":\"pop.exmail.qq.com\",\"port\":\"995\",\"sslEnable\":true,\"transport\":\"pop3\"}";
					//String sendproperStr = "{\"host\":\"smtp.exmail.qq.com\",\"port\":\"465\",\"sslEnable\":true,\"transport\":\"smtp\"}";

					
					UserEmailDTO dto = new UserEmailDTO(account, pass, null);
					
					/** 发送协议 */
					EmailSetDTO emailGetDto = new EmailSetDTO();
					/** 接收协议 */
					EmailSetDTO emailSendDto = new EmailSetDTO();
					
					JSONObject getproperJson = JSONObject.fromObject(getproperStr);
					emailGetDto = (EmailSetDTO) JSONObject.toBean(getproperJson, EmailSetDTO.class);
					
					JSONObject sendproperJson = JSONObject.fromObject(sendproperStr);
					emailSendDto = (EmailSetDTO) JSONObject.toBean(sendproperJson, EmailSetDTO.class);
					
					PropertiesUtils propertiesUtils = new PropertiesUtils(emailSendDto, emailGetDto);
					PropertiesDTO propertiesDto = propertiesUtils.getProperties();
					
					EmailUtils emailUtils = new EmailUtils(propertiesDto, dto);
					
					//TODO 设定自定义的邮件head头
					final JSONObject jsonObj = JSONObject.fromObject(extendMap);
					
					//TODO 发送邮件
					AddressDTO from = new AddressDTO(account, account);
					SendEmailDTO sendEmailDto = new SendEmailDTO(emailUtils, null, from, toCcBccAddress, title, content, null, fileJsonArr, jsonObj.toString());

					sendEmail(sendEmailDto);
				
				}catch(Exception e){
					e.printStackTrace();
				}
				
				return true;
			}
		});
	}
	
	/**
	 * 
	 * @param sendEmailDto
	 * @return
	 */
	private Boolean sendEmail(SendEmailDTO sendEmailDto){
		Boolean flag = false;
		
		/** 图片 */
		List<File> imgList = new ArrayList<File>();
		/** 附件 */
		List<File> fileList = new ArrayList<File>();
		/** 扩展字段 */
		Map<String, String> extendMap = new HashMap<String, String>();
		
		EmailUtils emailUtils = sendEmailDto.getEmailUtils();
		try{
			boolean sendResult = emailUtils.sendConnect();
			if(sendResult){
				/** 图片 */
				if(StringUtils.isNotBlank(sendEmailDto.getImgJsonArr())){
					imgList = downFile(sendEmailDto.getImgJsonArr());
				}
				/** 附件 */
				if(StringUtils.isNotBlank(sendEmailDto.getFileJsonArr())){
					fileList = downFile(sendEmailDto.getFileJsonArr());
				}
				/** 扩展字段 */
				if(StringUtils.isNotBlank(sendEmailDto.getExtendJsonStr())){
					JSONObject jsonOjb = JSONObject.fromObject(sendEmailDto.getExtendJsonStr());
					Set<?> keySet = jsonOjb.keySet();
					
					for (Object object : keySet) {
						String key = (String)object;
						String value = (String)jsonOjb.get(key);
						extendMap.put(key, value);
					}
				}
				//TODO 发送邮件
				logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>发送邮件");
				Boolean result = emailUtils.sendEmail(sendEmailDto.getUuid(), sendEmailDto.getToCcBccAddress(), sendEmailDto.getMessageTitle(), sendEmailDto.getMessageContent(), imgList, fileList, extendMap);
				if(result){
					flag = result;
				}

			}
		}catch(Exception e){
			e.printStackTrace();
		} finally {
			if(imgList != null){
				for (File file : imgList) {
					if(file.exists()){
						file.delete();
					}
				}
			}
			
			if(fileList != null){
				for (File file : fileList) {
					if(file.exists()){
						file.delete();
					}
				}
			}
		} 
		return flag;
	}
	
	/**
	 * 下载文件
	 * @param pathJosnArr
	 * @return
	 */
	private static List<File> downFile(String pathJosnArr){
		List<File> fileList = new ArrayList<File>();
		
		JSONArray jsonArray = JSONArray.fromObject(pathJosnArr);
		for (Object object : jsonArray) {

			JSONObject jsonObject = JSONObject.fromObject(object);
			
			String urlStr = jsonObject.getString("path");
			String fileName = jsonObject.getString("name");
			String savePath = DownLoadUtils.getDownPath();
			
			String localPath = DownLoadUtils.downLoadFromUrl(urlStr, fileName, savePath);
			
			File file = new File(localPath);
			if(file.exists()){
				fileList.add(file);
			}
		}
		return fileList;
	}
}
